# -*- coding: utf-8 -*-
# @Time    : 2024/1/11  16:35
# @Author  : zhanghao
# @FileName: slave.py
# @Software: PyCharm
"""
    Description: 子任务
"""
from PyQt6.QtCore import pyqtSignal
from fitz import fitz
from multiprocessing import Process, Pipe

from domain.table_info import TableInfo
from domain.signal_unit import SignalUnit
from helper.file_helper import FileHelper
from helper.status import Status
from helper.event_type import EventType
from core.paddle_ocr import PaddleOcr
from core.ocr_result import OcrResult
from core.rule_actuator import RuleActuator
from config.logger import Logger
from config.config import Config

import os


class Worker(Process):
    logger = Logger().get()

    paddle_ocr = PaddleOcr()
    config: Config
    rule_actuator: RuleActuator

    conn: Pipe

    def __init__(self, conn: Pipe, config: Config):
        super().__init__()
        self.conn = conn
        self.config = config
        self.rule_actuator = RuleActuator(self.config)
        self.logger.info('worker 初始化成功......')

    def run(self):
        self.logger.info(str(os.getpid()) + 'config version:' + self.config.getVersion())
        self.logger.info(str(os.getpid()) + ' worker 开始接收任务......')
        while True:
            deal_data = self.conn.recv()
            self.logger.info('worker 接收到任务：' + str(deal_data.idx))
            if deal_data:
                self.work(deal_data)

    def work(self, deal_data) -> None:
        # event--START_PROCESS
        event = SignalUnit.build(EventType.START_PROCESS, Status.PROCESSING, deal_data)
        self.conn.send(event)
        self.logger.info('开始处理任务' + deal_data.before_name)
        self.logger.info(event)

        # 清除缓存
        self.clearCacheDir()

        try:
            self.logger.info('开始处理文件: ' + deal_data.before_name)
            file_type = FileHelper.getFileType(deal_data.before_name)
            # 判断文件类型
            if FileHelper.fetchFileType(deal_data.before_name) == 1:
                content = self.processPdf(deal_data)
                self.innerProcess(content, file_type, deal_data)
            elif FileHelper.fetchFileType(deal_data.before_name) == 2:
                content = self.processImg(deal_data)
                self.innerProcess(content, file_type, deal_data)
            else:
                self.processOther(deal_data)
                deal_data.status = Status.FAILED
                deal_data.after_name = '不支持该文件类型'
                deal_data.operate = True

        except fitz.FileNotFoundError:
            deal_data.status = Status.FAILED
            deal_data.after_name = '文件不存在'
            deal_data.operate = True
            self.logger.error('文件不存在：', deal_data.before_name)

        except Exception as e:
            self.logger.error('处理异常，文件：', deal_data.before_name)
            deal_data.status = Status.FAILED
            deal_data.after_name = '未知异常'
            deal_data.operate = True
            self.logger.exception('未知异常：', e)

        finally:
            # event--END_PROCESS
            event = SignalUnit.build(EventType.END_PROCESS, deal_data.status, deal_data)
            self.conn.send(event)
            self.logger.info('处理结果111:')
            self.logger.info(event)

            # 清除缓存
            self.clearCacheDir()

    # 处理pdf
    def processPdf(self, data: TableInfo):
        return self.paddle_ocr.processPdf(data.before_name)

    # 处理图片
    def processImg(self, data: TableInfo):
        return self.paddle_ocr.processImg(data.before_name)

    # 未知文件
    def processOther(self, data: TableInfo):
        text_line = []
        ocr_result = OcrResult(text_line)
        return ocr_result

    def innerProcess(self, content: OcrResult, file_type, data: TableInfo):
        new_file_name = self.rule_actuator.processContent(content)
        self.logger.info('innerProcess new_file_name:' + new_file_name)
        # 对文件重命名
        self.rule_actuator.doRename(new_file_name, data.before_name, file_type)

        # 重新组装data数据
        if new_file_name:
            data.status = Status.SUCCESS
            data.after_name = new_file_name + file_type
        else:
            data.status = Status.FAILED
            data.after_name = '没有对应规则'
            data.operate = True

        return data

    def clearCacheDir(self):
        folder_path = self.paddle_ocr.getTempDir()

        if os.path.exists(folder_path):
            file_list = os.listdir(folder_path)

            for file_name in file_list:
                file_path = os.path.join(folder_path, file_name)
                # 判断是否为文件
                if os.path.isfile(file_path):
                    # 删除文件
                    os.remove(file_path)
